#!/bin/bash

# Check we're running as root
if [ "$(id -u)" != "0" ]; then
  echo "The backup script must be run as root"
  exit 1
fi

if [ ! -d /opt/datastore/db/backups ]; then
  logger -t db_backup -p user.err "DB backup not started as db backup directory does not exist"
  exit 1
fi
  
dateStr=`date +%Y%m%d%H%M`
backup_folder=/opt/datastore/db/backups/${dateStr}
mysql_bkp_folder="${backup_folder}/mysql"
mongo_bkp_folder="${backup_folder}/mongo"
cassandra_bkp_folder="${backup_folder}/cassandra"
mkdir -p ${backup_folder} ${mongo_bkp_folder} ${mysql_bkp_folder} ${cassandra_bkp_folder}
if [ $? -ne 0 ]; then
  logger -t db_backup -p user.err "DB backup not started as failed to create backup directory"
  rm -fr backup_folder
  exit 1
fi

/usr/bin/nodetool clearsnapshot
/usr/bin/nodetool -p 7199 snapshot audit  system  compliance  metrics  system_auth -t ${dateStr}

for LINE in `/bin/ls /var/lib/cassandra/data/*/* -d`
	do
	    LINE=$(echo "$LINE" | sed -e 's/[[:space:]]*//')
	    DEST=$(echo "$LINE" | sed -e "s#^\/var\/lib\/cassandra\/data/#$cassandra_bkp_folder/#")
		mkdir -p $DEST
		if [ -d "$LINE/snapshots/${dateStr}" ]; then
			mv $LINE/snapshots/${dateStr}/* $DEST >/dev/null 2>&1
		fi
	done

/usr/bin/nodetool clearsnapshot
---------------------------------------
Backup:
1. Create required directories. 
2. Clear old snapshots. # nodetool clearsnapshot
3. create snapshot with current name along with keyspace name. # nodetool -p 7199 snapshot audit  system  compliance  metrics  system_auth -t 000
4. copy each keyspace and column family snapshots to /opt/datastore/db/backups/

Restore:
1. Make sure backup data exists.
2. take backup of /var/lib/cassandra/data to some temp, so that next time itteration should be removing it.(Optional)
3. service cassandra stop; Clear existing SSTTables for all column families.
4. find /var/lib/cassandra/data/ -name "snapshots" -type d -exec rm -fr {} \;
5. find /var/lib/cassandra/data/ -name "*.db" -exec rm -fr {} \;

#!/bin/bash
#for LINE in `find /opt/datastore/db/backups/201410031626/cassandra/ -name "*.db"`
for LINE in `/bin/ls /opt/datastore/db/backups/201410031626/cassandra/*/* -d`
	do
	    LINE=$(echo "$LINE" | sed -e 's/[[:space:]]*//')
	    DEST=$(echo "$LINE" | sed -e 's/^\/opt\/datastore\/db\/backups\/201410031626\/cassandra/\/var\/lib\/cassandra\/data/g')
	    if [ ! -d "$DEST" ]; then
	    	mkdir -p $DEST
	    fi
	    rm -fr $DEST/*
		cp -fr $LINE/* $DEST >/dev/null 2>&1
	done
chown 644 /var/lib/cassandra/data/ -R
chown cassandra.cassandra /var/lib/cassandra/data/ -R
service cassandra stop
sleep 3
service cassandra start
echo "Restored backup: 201410031626"
